package com.spongebob.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spongebob.Vo.Shiro;
import com.spongebob.dao.RoleManageMapper;
import com.spongebob.pojo.CustomerService;
import com.spongebob.service.CustomerServiceService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;


/**
 * 自定义realm
 *
 * @author shengwu ni
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Resource
    private CustomerServiceService customerServiceService;
    @Resource
    private RoleManageMapper roleManageDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取用户名
        String email = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 给该用户设置角色，角色信息存在 t_role 表中取
        Shiro shiro = roleManageDao.getRole(email);
        Set s = shiro.getPermission();

//        System.out.println(s);
//        authorizationInfo.setRoles(Collections.singleton(shiro.getRoleName()));
        // 给该用户设置权限，权限信息存在 t_permission 表中取
        authorizationInfo.setStringPermissions(shiro.getPermission());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从token获取用户名,从主体传过来的认证信息中获取
        //加这一步的目的是在post请求时会先进入认证然后再到请求。
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        // 根据 Token 获取用户名，如果您不知道该 Token 怎么来的，先可以不管，下文会解释
        String email = (String) authenticationToken.getPrincipal();

        // 根据用户名从数据库中查询该用户
        QueryWrapper<CustomerService> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        CustomerService one = customerServiceService.getOne(queryWrapper);
        if (one != null) {
            // 把当前用户存到 Session 中
            one.setState("在线");
            customerServiceService.updateById(one);
            String password = one.getPassword();
            one.setPassword(null);
            SecurityUtils.getSubject().getSession().setAttribute("user", one);
            // 传入用户名和密码进行身份认证，并返回认证信息
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(one.getEmail(), password, "myRealm");

            return authcInfo;
        } else {
            return null;
        }
    }
}
